<template>
    <div>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item index="0">
          <img
            style="width: 100px"
            src="../images/result@2.png"
            alt="Element logo"
          />
        </el-menu-item>
        <el-menu-item index="1">
          <router-link to="/">首页</router-link>
        </el-menu-item>
        <el-menu-item index="2" :disabled="isGuest">
          <router-link to="/cart" @click.prevent="checkLogin">购物车</router-link>
        </el-menu-item>
        <el-menu-item index="3" :disabled="isGuest">
          <router-link to="/other" @click.prevent="checkLogin">订单</router-link>
        </el-menu-item>
        <el-menu-item index="4">
          <router-link to="/about">关于</router-link>
        </el-menu-item>
        <div class="flex-grow" />
        <el-menu-item index="5" v-if="!isGuest">{{ name }},欢迎你！</el-menu-item>
        <el-menu-item index="6" v-if="isGuest">
          <router-link to="/login">登录</router-link>
          /
          <router-link to="/register">注册</router-link>
        </el-menu-item>
        <el-menu-item index="7" v-else @click="goback()">退出</el-menu-item>
      </el-menu>
    </div>
  </template>
  
  <script>

  import { ElMessage } from 'element-plus';
  
  export default {
    data() {
      return {
        name: '游客',
        activeIndex: '1',
      };
    },
    computed: {
      isGuest() {
        return this.name === '游客';
      },
    },
    mounted() {
      const username = sessionStorage.getItem('username');
      this.name = username || '游客';
    },
    methods: {
      goback() {
        this.name = '游客';
        sessionStorage.setItem('username', null);
        this.$emit('logout'); // 触发事件，通知 MyList 组件用户已退出登录
      },
      handleSelect() {
        // Add logic to handle menu item selection if needed
      },
      checkLogin() {
        if (this.isGuest) {
          ElMessage({
            message: '您需要登录才能使用这个功能',
            type: 'warning',
          });
        }
      },
    },
  };
  </script>
  
  <style>
  a:-webkit-any-link {
    text-decoration: none;
  }
  .flex-grow {
    flex-grow: 1;
  }
  </style>